<?php
/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace frontend\controllers;

use builder\base\Http;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\Controller;

abstract class BaseController extends Controller
{
    use Http;

    /**
     * HTTP METHOD
     * @var array Verbs to specify the actions.
     */
    public $actionVerbs = [];

    /**
     * 只有游客可以访问
     * @var array Define actions that don't require authorization.
     */
    public $guestActions = [];

    /**
     * 只有游客和登录用户可以访问
     * @var array The guest and authenticated users can access current action.
     */
    public $publicActions = [];

    /**
     * {@inheritDoc}
     */
    public function behaviors()
    {
        return array_merge(
            $this->verbsFilter(),
            $this->accessControlFilter()
        );
    }

    /**
     * This is action verbs filters.
     * @return array
     */
    public function verbsFilter()
    {
        if (!empty($this->actionVerbs)) {
            return [
                'verbs' => [
                    'class' => VerbFilter::class,
                    'actions' => $this->actionVerbs,
                ],
            ];
        } else {
            return [];
        }
    }

    /**
     * This is access control filters.
     * @return array
     */
    public function accessControlFilter()
    {
        if (
            !in_array($this->action->id, $this->guestActions, true)
            && !in_array($this->action->id, $this->publicActions, true)
        ) {
            // 只有认证用户可以访问
            return [
                'access' => [
                    'class' => AccessControl::class,
                    'only' => [$this->action->id],
                    'rules' => [
                        [
                            'allow' => true,
                            'roles' => ['@'],
                        ],
                    ],
                ],
            ];
        } elseif (in_array($this->action->id, $this->guestActions, true)) {
            // 只有游客可以访问
            return [
                'access' => [
                    'class' => AccessControl::class,
                    'only' => [$this->action->id],
                    'rules' => [
                        [
                            'allow' => true,
                            'roles' => ['?'],
                        ],
                    ],
                ],
            ];
        } else {
            // 游客和认证用户都可以访问
            return [];
        }
    }
}